#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/1/1 22:25
# @Author  : leon yan
# @Site    : 
# @File    : AlarmList.py
# @Software: PyCharm
import datetime
import json
import time
from enum import Enum

import xlwt
from PyQt5.QtCore import pyqtSlot, Qt, QStringListModel, QDir
from PyQt5.QtWidgets import (QApplication, QMainWindow, QDesktopWidget, QMessageBox, QAbstractItemView, QCheckBox,
                             QHBoxLayout, QWidget, QTableWidgetItem, QPushButton, QFileDialog)

import Globalist as gl
from lib.qpagenation import QPagenation
from lib.qsqledit import QSQL, DeleteDbRecord2, UpdateDB
from lib.qtablewidgetobj import QTableWidgetObj
# from lib.qprintertsc import Qprintertsc
from resource.AlarmList_ui import Ui_QWFormTable


# from LabelPrint import QLabelPrint


# 各单元格的类型(每一列)
class CellType(Enum):
    ctA = 1000
    ctB = 1001
    ctC = 1002
    ctD = 1003
    ctE = 1004
    ctF = 1005
    ctG = 1006
    ctH = 1007
    ctI = 1008
    ctJ = 1009
    ctK = 1010
    ctL = 1011
    ctM = 1012
    ctN = 1013
    ctO = 1014
    ctP = 1015


# 各字段在表格中的列号
class FieldColNum(Enum):
    colA = 0
    colB = 1
    colC = 2
    colD = 3
    colE = 4
    colF = 5
    colG = 6
    colH = 7
    colI = 8
    colJ = 9
    colK = 10
    colL = 11
    colM = 12
    colN = 13
    colO = 14
    colP = 15


'''分页处理'''


def doPageNation(lst, page, pagenum):
    obj = QPagenation(lst, page, pagenum)
    return obj.show(), obj.paginate(page, pagenum)


def doTotalPage(totalCounter, PageSize):
    aa = totalCounter % PageSize
    aa2 = totalCounter // PageSize
    if aa > 0:
        return aa2 + 1
    else:
        return aa2


def write_data_to_excel(name, lstData):
    # 实例化一个Workbook()对象(即excel文件)
    wbk = xlwt.Workbook()
    # 新建一个名为Sheet1的excel sheet。此处的cell_overwrite_ok =True是为了能对同一个单元格重复操作。
    sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True)
    # 获取当前日期，得到一个datetime对象如：(2016, 8, 9, 23, 12, 23, 424000)
    strCurrentTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
    for i in range(len(lstData)):
        for j in range(len(lstData[i])):
            sheet.write(i, j, lstData[i][j])
    wbk.save(name + "_" + strCurrentTime + '.xlsx')


class QAlarmList(QMainWindow, Ui_QWFormTable):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        # gl.init()
        self.setupUi(self)
        self.model = QStringListModel(self)
        self.pagenumber.setText("")
        self.recordamount.setText("")
        self.searchAlarm.setText('')
        self.searchAlarm.returnPressed.connect(self.on_btnSearch_clicked)
        ''''''
        self.objtablewidget = QTableWidgetObj()

        '''2021-01-21'''
        '''表格用'''
        self._tableInitialized = False
        self.rowCount = 0
        self._tabStyle()
        self.bTableLineSelected = 0
        self.tableWidgetLine = []

        self.orderSeq = "desc"
        self.searchWhere = " 1 = 1 "
        self.strWhere = ""
        self.byOrder = " order by id "
        self.totalCounter = 0
        ''''''
        self.DbResult = None
        ''''''
        self.PageSize = 30
        self.totalPage = 1
        self.needPage = 1
        self.before = 0
        self.next = 0
        self.current = 0
        ''''''
        self.pcsTable()
        self.CurrentTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        ''''''

    def __del__(self):
        print("AlarmList is deleted")

    def pcsTable(self):
        if self.searchWhere:
            self.strWhere = self.searchWhere
        else:
            self.strWhere = " 1 =1 "
        retDbResult = self.rdDwsDetail("AlarmLog", None, None, None, self.strWhere)  # 读数据库
        self.totalCounter = retDbResult[1]
        self.pcsPageNation(retDbResult[0])
        ''''''
        self.DbResult = retDbResult[0]
        # print(self.DbResult)

    '''读数据库'''

    def rdDwsDetail(self, tblName, dictCondition=None, strQueryType=None, eNum=None, strWhere=None):
        strOrder = self.byOrder + self.orderSeq
        aFields = ['id', 'AlarmTime', 'Descriptions', 'Position', 'Code', 'Operator']
        obj = QSQL(tblName, dictCondition, strOrder, aFields, strQueryType, eNum, strWhere)
        rdData = obj.showLst()
        jd = json.loads(rdData)
        return jd, len(jd)

    '''Json转换,分页'''

    def pcsPageNation(self, lst):
        retLst = doPageNation(lst, self.needPage, self.PageSize)  # 分页处理
        newLst = retLst[0][0]
        self.totalPage = doTotalPage(self.totalCounter, self.PageSize)
        self.before = retLst[1]['before']
        self.current = retLst[1]['current']
        self.next = retLst[1]['next']
        '''表格显示'''
        self.do_OpenTable(newLst)
        self.pagenumber.setText(str(self.current) + " / " + str(self.totalPage))
        self.recordamount.setText(str(self.totalCounter))

    def _tabStyle(self):
        # #表头颜色
        # headColTab = self.tableWidget.horizontalHeader()
        # headColTab.setStyleSheet("QHeaderView::section{background:#ffffff;color:#454545}")
        # headRowTab = self.tableWidget.verticalHeader()
        # headRowTab.setStyleSheet("QHeaderView::section{background:#ffffff;color:#454545}")
        #
        # #设定列宽
        self.tableWidget.horizontalHeader().resizeSection(0, 60)  # 选择
        self.tableWidget.horizontalHeader().resizeSection(1, 80)  # id
        self.tableWidget.horizontalHeader().resizeSection(2, 200)  # alarm time
        self.tableWidget.horizontalHeader().resizeSection(3, 550)  # descriptions
        self.tableWidget.horizontalHeader().resizeSection(4, 120)  # position
        self.tableWidget.horizontalHeader().resizeSection(5, 100)  # code
        self.tableWidget.horizontalHeader().resizeSection(6, 90)  # operator
        self.tableWidget.setContentsMargins(0, 0, 0, 0)
        self.tableWidget.verticalHeader().setDefaultSectionSize(40)  # 缺省行高
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        '''slot signal'''
        self.tableWidget.horizontalHeader().sectionClicked.connect(self.HorSectionClicked)  # 表头单击信号
        # self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)  # 允许右键产生子菜单
        # self.tableWidget.doubleClicked.connect(self._editRow)
        # self.tableWidget.customContextMenuRequested.connect(self.generateMenu)  # 右键菜单

        self.rowCount = 0
        self.tableWidgetLine = []

    def _editRow(self):
        CurrentRow = self.tableWidget.currentRow()
        dbId = int(self.tableWidget.item(CurrentRow, 1).text())
        self.currentDbId.emit(dbId)

    def generateMenu(self, pos):
        actionItem = self.objtablewidget.generateEditMenu(pos, self.tableWidget)
        if actionItem == 'Edit': self._editRow()

    '''点击表头信号'''

    @pyqtSlot(int)
    def HorSectionClicked(self, index):
        if index == 0:
            for line in self.tableWidgetLine:
                if line[0].isChecked():
                    line[0].setChecked(False)
                else:
                    line[0].setChecked(True)
        if 0 < index <= 4:
            self.do_order(index)

    def _rdRowValue(self, rowNum):
        lst = []
        for i in range(self.COL_COUNT):
            item = self.itemModel.item(rowNum, i)
            if item:
                aa = (item.text())
            else:
                aa = None
            lst.append(aa)
        return lst

    '''新建或打开至表格'''

    def do_OpenTable(self, tabs):
        # 先清除列表
        self.objtablewidget.delAllTablineM2(self.tableWidgetLine, self.tableWidget)
        self.rowCount = self.tableWidget.rowCount()  # 表格行数
        # 添加至表格
        for i in range(len(tabs)):
            a0 = tabs[i][0]  #
            a1 = tabs[i][1]  #
            a2 = tabs[i][2]  #
            a3 = tabs[i][3]  #
            a4 = tabs[i][4]  #
            a5 = tabs[i][5]  #
            # a5 = str(tabs[i][5])  #
            # a6 = tabs[i][6]  #
            # a7 = tabs[i][7]  #
            # a8 = tabs[i][8]  #
            # a9 = tabs[i][9]  #
            # a10 = tabs[i][10]  #
            # a11 = tabs[i][11]  #
            args = [a0, a1, a2, a3, a4, a5]
            NewRowCount = self.rowCount + i
            self.tableWidget.insertRow(NewRowCount)
            self.__createItemsRow(NewRowCount, *args)

    '''创建表格并显示'''

    def __createItemsRow(self, rowNo, *args):
        nameTable = self.tableWidget
        # a0
        # create an cell widget
        chkBox = QCheckBox(nameTable)
        h = QHBoxLayout()
        h.setAlignment(Qt.AlignCenter)
        h.addWidget(chkBox)
        w = QWidget()
        w.setLayout(h)
        nameTable.setCellWidget(rowNo, 0, w)

        # a
        item = QTableWidgetItem(str(args[0]), CellType.ctB.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.AlignCenter)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colB.value, item)
        # b
        item = QTableWidgetItem(str(args[1]), CellType.ctC.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colC.value, item)
        # c
        item = QTableWidgetItem(str(args[2]), CellType.ctD.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colD.value, item)

        # d
        item = QTableWidgetItem(str(args[3]), CellType.ctE.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colE.value, item)

        # e
        item = QTableWidgetItem(str(args[4]), CellType.ctF.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colF.value, item)

        # f
        item = QTableWidgetItem(str(args[5]), CellType.ctG.value)
        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = item.font()
        font.setPointSize(8)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)  # 不允许编辑文字
        nameTable.setItem(rowNo, FieldColNum.colG.value, item)

        self._tableInitialized = True
        self.tableWidgetLine.append([chkBox, args[0], args[1], args[2], args[3], args[4], args[5]])

        # if args[10]:
        #     for i in range(1, 10):
        #         self.tableWidget.item(rowNo, i).setBackground(QBrush(QColor(88, 194, 38)))

    '''
    SLOT 信号链接
    排序， 翻页链接
    '''

    @pyqtSlot(int)
    def do_order(self, oderIndex):
        if oderIndex == 1:
            self.byOrder = "order by id "
            if self.orderSeq == "asc":
                self.orderSeq = "desc"
            else:
                self.orderSeq = "asc"
        if oderIndex == 2:
            self.byOrder = "order by AlarmTime "
            if self.orderSeq == "asc":
                self.orderSeq = "desc"
            else:
                self.orderSeq = "asc"
        if oderIndex == 3:
            self.byOrder = "order by Descriptions "
            if self.orderSeq == "asc":
                self.orderSeq = "desc"
            else:
                self.orderSeq = "asc"
        if oderIndex == 4:
            self.byOrder = "order by Position "
            if self.orderSeq == "asc":
                self.orderSeq = "desc"
            else:
                self.orderSeq = "asc"
        if oderIndex == 5:
            self.byOrder = "order by Code "
            if self.orderSeq == "asc":
                self.orderSeq = "desc"
            else:
                self.orderSeq = "asc"

        self.needPage = 1
        self.pcsTable()

    @pyqtSlot()
    def on_btnFirst_clicked(self):
        if self.current > 1:
            self.needPage = 1
            self.pcsTable()

    @pyqtSlot()
    def on_btnBefore_clicked(self):
        if self.current > 1:
            self.needPage = self.before
            self.pcsTable()

    @pyqtSlot()
    def on_btnNext_clicked(self):
        if self.current < self.totalPage:
            self.needPage = self.next
            self.pcsTable()

    @pyqtSlot()
    def on_btnLast_clicked(self):
        if self.current < self.totalPage:
            self.needPage = self.totalPage
            self.pcsTable()

    '''
    搜索，删除，新建
    '''

    @pyqtSlot()
    def on_btnSearch_clicked(self):
        self.needPage = 1
        strWhere = "1 = 1"
        strWhere = strWhere + " and Descriptions like '%" + self.searchAlarm.text() + "%' "
        self.searchWhere = strWhere
        self.pcsTable()

    @pyqtSlot()
    def on_btnDelete_clicked(self):
        tbllineObj = self.tableWidgetLine
        LstNeedDeleteId = []
        for line in tbllineObj:
            if line[0].isChecked():
                LstNeedDeleteId.append(line[1])
        if LstNeedDeleteId is None or LstNeedDeleteId == []:
            QMessageBox.information(self, "Tips", "No rows selected to delete")
            return
        '''删除确认?'''
        ret = QMessageBox.question(self, "Delete confirmation", "Are you sure you want to delete the selected list rows?")
        if ret != QMessageBox.Yes:
            return
        DeleteDbRecord2('AlarmLog', LstNeedDeleteId)
        ''''''
        self.pcsTable()

    @pyqtSlot()
    def on_btnDownload_clicked(self):
        if self.DbResult == [] or self.DbResult is None:
            return
        curDir = QDir.currentPath()  # 获取当前路径
        try:
            aFile, filt = QFileDialog.getSaveFileName(self,
                                                      "Open files", curDir, "All files(*.xlsx)")
            write_data_to_excel(aFile, self.DbResult)
        except BaseException as e:
            print(e)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    thisWindowObj = QAlarmList()

    thisWindowObj.show()
    sys.exit(app.exec_())
